<template>
  <div class="download page page_padding">
    <h1 class="tips">Download</h1>
    <br />
    <h2 class="tips">输入分享码</h2>
    <h3 class="tips">
      <InputBox
        icon="ri-lock-line"
        placeholder="分享码"
        type="text"
        v-model:value="shareKey"
        key="shareKey"
        :on-enter="download"
        :button="`下载`"
        :button-on-click="download"
      />
    </h3>
    <br />
    <h2 class="tips">下载记录</h2>
    <transition-group name="slide-fade">
      <div v-for="file in files" :key="file.name" class="file_clip">
        {{ file.name }}
        <span class="time">{{ file.time }}</span>
      </div>
    </transition-group>
  </div>
</template>

<script>
import { reactive, toRefs } from "vue";
import InputBox from "../components/InputBox.vue";
import { nException, nSuccess } from "../components/TipsDialog";
import { apis } from "../api";

export default {
  components: { InputBox },
  setup() {
    const data = reactive({
      shareKey: "",
      files: []
    })

    const download = () => {
      if (data.shareKey.length > 0) {
        apis.download(data.shareKey).then(res => {
          nSuccess("开始下载")
          let now = new Date();
          const filename = res.headers["content-disposition"];
          const rawname = decodeURIComponent(filename.split("filename=")[1])
          data.files.push({ name: rawname, time: now.toLocaleTimeString() })

          const blob = new Blob([res.data]);
          var downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob);
          downloadElement.href = href;
          downloadElement.download = rawname;
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement);
          window.URL.revokeObjectURL(href);
        }).catch(() => {
          nException("分享码不可用")
        })
      } else {
        nException("分享码不可为空")
      }
    }

    return { ...toRefs(data), download }
  }
}
</script>

<style scoped lang="less">
.download {
  min-height: 100vh;
}

.file_clip {
  background-color: rgba(0, 0, 0, 0.1);
  padding: 16px;
  position: relative;
  border-radius: 10px;
  word-break: break-all;

  .time {
    float: right;
  }

  &:hover {
    background-color: rgba(0, 0, 0, 0.2);
  }
}
</style>